<template>
	<div class="container">
		<JxNavbar title='登录' />
		<div class="main">
			<view class="title">欢迎登录</view>
			<div class="login-box" v-if="loginType === 'smsCode'">
				<div class="input-item mobile uv-border-bottom">
					<text>+86</text>
					<input class="item-input" placeholder="请输入手机号" v-model="formData.mobile" />
				</div>

				<div class="input-item code uv-border-bottom">
					<input class="item-input" placeholder="请输入验证码" v-model="formData.smsCode" />
					<view class="verify-code" :class="{ 'verify-code-disabled': second > 0 }" @tap="getMobileCode">{{ getVerifyCodeText }}</view>
				</div>
			</div>

			<div class="login-box" v-else>
				<div class="input-item uv-border-bottom">
					<input class="item-input" placeholder="请输入账号" v-model="formData.account" />
				</div>

				<div class="input-item uv-border-bottom">
					<input password class="item-input" placeholder="请输入密码" v-model="formData.password" />
				</div>
			</div>

			<p class='tips'>{{ loginType === 'smsCode' ? `未注册的手机号验证后自动创建${config.projectName}账号` : '' }}</p>
			<button class="uv-reset-button on-submit-btn" :class="{'not-active': validateFormData['length']}" @click="loginSmsOrPassword">登录</button>

			<div class="login-type">
				<text @click="changeLoginType">{{ loginType === 'smsCode' ? '密码登录' : '验证码登录' }}</text>
				<text @click="handleQuestion">遇到问题</text>
			</div>
		</div>

		<div class="login-bottom safe-area-inset-bottom">
			<button v-if="checkbox" class="login-type uv-reset-button" open-type="getPhoneNumber" @getphonenumber="weixinLogin">
				<i class='iconfont icon-weixin'></i>
				<text>微信</text>
			</button>

			<div v-else class="login-type" @click="agreeProtocol">
				<i class='iconfont icon-weixin'></i>
				<text>微信</text>
			</div>

			<view class="login-hint" :class="{ shaking }" @click="checkbox = !checkbox">
				<span class="iconfont icon-chenggong" :class="{ active: checkbox }"></span>
				<span>我已阅读并同意</span>
				<span class="link" @click.stop="navigateTo('privacy')">《隐私政策》</span>
				<span class="link" @click.stop="navigateTo('user')">《用户协议》</span>
				<span>并授权使用您的账号信息（如昵称、头像、收获地址）以便您统一管理</span>
			</view>
		</div>
	</div>
</template>

<script setup>
	import md5 from "md5"
	import { ref, computed } from 'vue'
	import sms from '@/api/sms/index.js'
	import config from '@/config/index.js'
	import auth from '@/api/auth/index.js'
	import tools from '@/utils/tools/index.js'
	import { useUserStore } from '@/store/user.js'
	import JxNavbar from '@/components/navbar/index.vue'

	const test = uni.$uv.test;
	const userStore = useUserStore();

	const second = ref(0);
	const shaking = ref(false);
	const checkbox = ref(false);
	const loginType = ref('smsCode');
	const formData = ref({ mobile: '', smsCode: '', account: '', password: '' })

	const validateFormData = computed(() => {
		const errors = [];
		switch (loginType.value) {
			case 'smsCode':
				const { mobile, smsCode } = formData.value;
				const checkMobile = test.mobile(mobile);
				const checkSmsCode = test.code(smsCode);
				!checkMobile && errors.push('请输入正确手机号');
				!checkSmsCode && errors.push('请输入正确验证码');
				break;
			case 'password':
				const { account, password } = formData.value;
				const checkAccount = test.mobile(account) || test.email(account)
				const checkPassword = test.rangeLength(password, [6, 16]);
				!checkAccount && errors.push('请输入正确账号');
				!checkPassword && errors.push('请输入正确密码');
		}
		return errors;
	})

	const getVerifyCodeText = computed(() => {
		if (second.value <= 0) {
			return '获取验证码';
		} else if (second.value < 10) {
			return '重新获取0' + second.value;
		} else {
			return '重新获取' + second.value;
		}
	})

	async function getMobileCode() {
		const { mobile } = formData.value;

		if (!test.mobile(mobile)) {
			return tools.toast({ title: '请输入正确手机号', });
		} else if (second.value) {
			return tools.toast({ title: `请在${second.value}秒后重试`, });
		}

		tools.loading();
		const response = await sms.sendSms({ mobile, name: 'login' });
		uni.hideLoading();
		if (response['code'] === 200) {
			second.value = 60;
			tools.toast({ title: '发送成功', icon: 'success' });
			let codeInterVal = setInterval(() => {
				second.value--;
				if (second.value <= 0) {
					clearInterval(codeInterVal)
					codeInterVal = null
				}
			}, 1000)
		}
	}

	async function loginSmsOrPassword() {
		if (validateFormData['value']['length']) {
			return tools.toast({ title: validateFormData.value[0] })
		}

		if (!agreeProtocol()) return;

		if (loginType.value === 'smsCode') {
			smsLogin();
		} else {
			passwordLogin();
		}
	}

	async function smsLogin() {
		tools.loading();
		const { smsCode, mobile } = formData.value;
		const codeResult = await tools.getLoginCode();
		const response = await auth.sms_login({ loginCode: codeResult['data'], smsCode, mobile });
		uni.hideLoading();
		if (response['code'] === 200) {
			loginSuccess(response);
		}
	}

	async function passwordLogin() {
		tools.loading();
		const { password, account } = formData.value;
		const codeResult = await tools.getLoginCode();
		const response = await auth.password_login({ loginCode: codeResult['data'], account, password: md5(password) });
		uni.hideLoading();
		if (response['code'] === 200) {
			loginSuccess(response);
		}
	}

	function changeLoginType() {
		loginType.value = loginType.value === 'password' ? 'smsCode' : 'password';
	}

	function handleQuestion() {
		uni.showActionSheet({
			itemList: ['联系客服'],
			success: (res) => {
				if (res.tapIndex === 0) {}
			},
		});
	}

	async function weixinLogin(e) {
		const mobileCode = e.detail.code;
		if (!mobileCode) return tools.toast({ title: '获取手机号失败' });

		tools.loading();
		const codeResult = await tools.getLoginCode();
		const response = await auth.wx_mobile_login({ loginCode: codeResult['data'], mobileCode });
		uni.hideLoading();
		if (response['code'] === 200) {
			loginSuccess(response);
		}
	}

	function loginSuccess(response) {
		const data = response['data'];
		uni.setStorageSync('token', response['data']['token']);
		tools.toast({
			title: '登录成功',
			icon: 'success',
			fun: () => {
				uni.navigateBack({ delta: 1 });
				userStore.init()
			}
		})
	}

	function agreeProtocol() {
		if (!checkbox.value) {
			uni.vibrateShort({});
			tools.toast({ title: '请先阅读并同意协议' });
			shaking.value = true;
			setTimeout(() => {
				shaking.value = false
			}, 1000);
		}
		return checkbox.value;
	}

	function navigateTo(type) {
		uni.navigateTo({
			url: '/pages/sub/my/protocol/index?type=' + type
		})
	}
</script>

<style lang="scss" scoped>
	.container {
		background: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		height: 100vh;

		.main {
			flex: 1;
			width: 640rpx;

			.title {
				font-size: 50rpx;
				font-weight: 500;
				margin-top: 8vh;
				margin-bottom: 100rpx;
			}

			.tips {
				margin-bottom: 60rpx;
				padding-top: 10rpx;
				font-size: 28rpx;
				color: $uv-tips-color;
			}

			.login-box {
				.input-item {
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: space-between;
					height: 90rpx;
					padding-top: 10rpx;
					margin-bottom: 15rpx;

					.item-input {
						flex: 1;
						height: 100%;
					}

					&.mobile {
						flex-shrink: 0;

						text {
							font-weight: 600;
							margin-right: 15rpx;
						}
					}

					&.code {
						flex-shrink: 0;

						.verify-code {
							color: $uv-primary;
							font-size: 26rpx;
							height: 55rpx;
							padding: 0 16rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							border-radius: 4px;
							border: 1px solid $uv-primary;
							white-space: nowrap;
						}

						.verify-code-disabled {
							color: $uv-tips-color;
							border: 1px solid $uv-border-color;
						}
					}
				}
			}

			.on-submit-btn {
				height: 85rpx;
				line-height: 85rpx;
				border-radius: 36px;
				background: $uv-primary;
				color: #fff;
				font-size: 32rpx;
			}

			.login-type {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				margin-top: 15px;

				text {
					color: $uv-content-color;
					font-size: 28rpx;
				}
			}
		}

		.login-bottom {

			.login-type {
				display: flex;
				flex-direction: column;
				align-items: center;
				margin-bottom: 50rpx;

				.icon-weixin {
					font-size: 70rpx;
					color: #07c160;
				}

				text {
					color: $uv-content-color;
					font-size: 26rpx;
				}
			}

			.login-hint {
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				align-items: center;
				padding: 30rpx 40rpx 0 40rpx;
				font-size: 26rpx;
				color: $uv-tips-color;
				line-height: 1.5;

				.link {
					color: $uv-primary;
				}

				.active {
					color: $uv-primary;
				}

				.icon-chenggong {
					padding-right: 5rpx;
					flex-shrink: 0;
					font-size: 38rpx;
				}
			}
		}
	}
</style>